from PIL import Image

def concatenate_images(image_path1, image_path2, output_path, direction='horizontal'):
    # 打开图片
    img1 = Image.open(image_path1)
    img2 = Image.open(image_path2)

    # 确定拼接方向
    if direction == 'horizontal':
        # 水平方向拼接，宽度相加，高度取最大值
        new_width = img1.width + img2.width
        new_height = max(img1.height, img2.height)
        new_image = Image.new('RGBA', (new_width, new_height))
        new_image.paste(img1, (0, 0))
        new_image.paste(img2, (img1.width, 0))
    elif direction == 'vertical':
        # 垂直方向拼接，高度相加，宽度取最大值
        new_width = max(img1.width, img2.width)
        new_height = img1.height + img2.height
        new_image = Image.new('RGBA', (new_width, new_height))
        new_image.paste(img1, (0, 0))
        new_image.paste(img2, (0, img1.height))
    else:
        raise ValueError("方向必须是 'horizontal' 或 'vertical'")

    # 保存拼接结果
    new_image.save(output_path)
    print(f"图片已保存至 {output_path}")

# 示例用法
concatenate_images('Main_results/2_fig2/1_trajectory.png','Main_results/2_fig2/2_scatters.png', 'Main_results/2_fig2/output.png', direction='horizontal')

